package flinkSql.time;

import bean.SensorReading;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.junit.Test;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

//TODO 事件事件语义
public class Flink_EventTime_DS {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        WatermarkStrategy<SensorReading> watermarkStrategy =
                WatermarkStrategy.<SensorReading>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                .withTimestampAssigner((SerializableTimestampAssigner<SensorReading>) (element, recordTimestamp) -> element.getTs() * 1000);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] s = value.split(",");
                    return new SensorReading(s[0], Long.parseLong(s[1]), Double.parseDouble(s[2]));
                })
                .assignTimestampsAndWatermarks(watermarkStrategy)
                .keyBy(SensorReading::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce((ReduceFunction<SensorReading>) (value1, value2) -> value2);

        tableEnv.createTemporaryView("sensor",input,$("id"),$("ts"),$("temp"));
//        Table table1 = tableEnv.fromDataStream(input);

        Table table = tableEnv.sqlQuery("select * from sensor");
        table.printSchema();
        tableEnv.toRetractStream(table, SensorReading.class).print();

        env.execute();
    }
}
